package com.android.clinic.app.ui.doctor;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.CustomerServiceInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.utils.DisplayUtil;
import com.android.clinic.app.utils.TimeUtils;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.gyf.barlibrary.ImmersionBar;
import com.kennyc.view.MultiStateView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by cheng on 2018/3/26.
 * 客服咨询
 */
public class CustomerServiceActivity extends BaseActivity implements OnRefreshListener {

    private SwipeToLoadLayout swipeToLoadLayout;
    private ListView listView;
    private CustomerServiceAdapter serviceAdapter;
    private int pageNum = 1; // 当前页数
    private List<CustomerServiceInfo> customerTempList = new ArrayList<>();
    private EditText etContent;

    private Timer timer;
    private TimerTask task;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_chat_listview;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ImmersionBar.with(this).keyboardEnable(true).init();
        setTitleBarTitle("管家");
        setTitleBarLeftResource(R.drawable.icon_back);
        swipeToLoadLayout = (SwipeToLoadLayout) findViewById(R.id.swipeToLoadLayout);
        listView = (ListView) findViewById(R.id.swipe_target);
        swipeToLoadLayout.setOnRefreshListener(this);

        etContent = (EditText) findViewById(R.id.et_content);
        serviceAdapter = new CustomerServiceAdapter();
        listView.setAdapter(serviceAdapter);
    }

    @Override
    protected void loadData() {
        super.loadData();
        getMessage();
    }

    /**
     * 获取消息
     */
    private void getMessage() {
        HttpClient.getHttpService().getMessage(ClinicApplication.getUserInfo().getId(),
                100, pageNum)
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        refreshComplete();
                        customerTempList.clear();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            List<CustomerServiceInfo> customerInfoList = JSON.parseArray(jsonObject.optJSONArray("result").toString(),
                                    CustomerServiceInfo.class);
                            int customerSize = customerInfoList.size();
                            if (customerSize > 0) {
                                setMultiStateView(MultiStateView.VIEW_STATE_CONTENT);
                                Collections.reverse(customerInfoList);
                                customerTempList.addAll(customerInfoList);
                                serviceAdapter.setCustomerInfoList(customerTempList);
                                listView.setSelection(customerInfoList.size());
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        refreshComplete();
                        showToast(message);
                    }
                });
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        new Handler().postDelayed(this::getMessage, 500);
    }

    private void refreshComplete() {
        if (swipeToLoadLayout.isRefreshing()) {
            swipeToLoadLayout.setRefreshing(false);
        }
    }

    private class CustomerServiceAdapter extends BaseAdapter {

        private final static int USER = 0x000001;
        private final static int SYSTEM = 0x000002;

        private List<CustomerServiceInfo> customerInfoList = new ArrayList<>();

        private void setCustomerInfoList(List<CustomerServiceInfo> customerInfoList) {
            this.customerInfoList = customerInfoList;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return  this.customerInfoList.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (this.customerInfoList.get(position).getType().equals("user")) {
                return USER;
            } else {
                return SYSTEM;
            }
        }

        @Override
        public CustomerServiceInfo getItem(int position) {
            return  this.customerInfoList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (getItemViewType(position) == USER) {
                UserViewHolder userHolder;
                if (null == convertView || null == convertView.getTag(R.id.tag_user)) {
                    convertView = LayoutInflater.from(CustomerServiceActivity.this).inflate(R.layout.item_chat_send_layout, null);
                    userHolder = new UserViewHolder();
                    userHolder.ivSendHead = (ImageView) convertView.findViewById(R.id.iv_send_head);
                    userHolder.tvSendText = (TextView) convertView.findViewById(R.id.tv_send);
                    userHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_send_time);
                    convertView.setTag(R.id.tag_user, userHolder);
                } else {
                    userHolder = (UserViewHolder) convertView.getTag(R.id.tag_user);
                }
                ImageLoaderUtils.getInstance().loadHeadImage(ClinicApplication.getUserInfo().getImgUrl(), userHolder.ivSendHead,
                        DisplayUtil.dip2px(45), DisplayUtil.dip2px(45));
                userHolder.tvSendText.setText(getItem(position).getMessage());
                userHolder.tvSendTime.setText(TimeUtils.getChatFormatTime(getItem(position).getCreateTime()));

            } else {
                SystemViewHolder systemHolder;
                if (null == convertView || null == convertView.getTag(R.id.tag_system)) {
                    convertView = LayoutInflater.from(CustomerServiceActivity.this).inflate(R.layout.item_chat_from_layout, null);
                    systemHolder = new SystemViewHolder();
                    systemHolder.ivFromHead = (ImageView) convertView.findViewById(R.id.iv_from_head);
                    systemHolder.tvFromText = (TextView) convertView.findViewById(R.id.tv_from);
                    systemHolder.tvFromTime = (TextView) convertView.findViewById(R.id.tv_from_time);
                    convertView.setTag(R.id.tag_system, systemHolder);
                } else {
                    systemHolder = (SystemViewHolder) convertView.getTag(R.id.tag_system);
                }
                ImageLoaderUtils.getInstance().loadHeadImage(R.mipmap.icon_app_logo,
                        systemHolder.ivFromHead, DisplayUtil.dip2px(45), DisplayUtil.dip2px(45));
                systemHolder.tvFromText.setText(getItem(position).getMessage());
                systemHolder.tvFromTime.setText(TimeUtils.getChatFormatTime(getItem(position).getCreateTime()));

            }
            return convertView;
        }

        class UserViewHolder {
            ImageView ivSendHead;
            TextView tvSendText, tvSendTime;
        }

        class SystemViewHolder {
            ImageView ivFromHead;
            TextView tvFromText, tvFromTime;
        }
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        if (v.getId() == R.id.btn_send) {
            if (etContent.getText().length() == 0) {
                showToast("发送内容不能为空!");
                return;
            }
            sendMessage(etContent.getText().toString().trim());
        }
    }

    /**
     * 添加本地临时数据
     * @param message
     */
    private void addTempChatList(String message) {
        CustomerServiceInfo chatInfo = new CustomerServiceInfo();
        chatInfo.setUserId(ClinicApplication.getUserInfo().getId());
        chatInfo.setType("user");
        chatInfo.setMessage(message);
        chatInfo.setCreateTime(System.currentTimeMillis());
        customerTempList.add(chatInfo);
        serviceAdapter.setCustomerInfoList(customerTempList);
        listView.setSelection(customerTempList.size());
    }

    /**
     * 发送消息
     * @param message
     */
    private void sendMessage(final String message) {
        HttpClient.getHttpService().sendMessage(ClinicApplication.getUserInfo().getId(), message)
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        addTempChatList(message);
                        etContent.setText("");
                        hideKeyboard();
                        if (null == timer) {
                            timer = new Timer();
                            task = new TimerTask() {
                                @Override
                                public void run() {
                                    getMessage();
                                }
                            };
                            timer.schedule(task, 5000, 5000);
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null || task != null) {
            timer.cancel();
            task.cancel();
        }
    }
}
